package com.example.demo.msg.aio.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class WriteHandle  implements CompletionHandler<Integer,ByteBuffer> {

    private AsynchronousSocketChannel channel;


    public WriteHandle(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer integer, ByteBuffer byteBuffer) {
        if(byteBuffer.hasRemaining()){
            channel.write(byteBuffer,byteBuffer,this);
        }else{

            //创建新的Buffer
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            //异步读  第三个参数为接收消息回调的业务Handler
            channel.read(readBuffer, readBuffer, new ReadHandle(channel));
        }

    }

    @Override
    public void failed(Throwable throwable, ByteBuffer byteBuffer) {
        try {
            channel.close();
        } catch (IOException e) {

        }

    }
}